<?php

namespace App\Admin\Controllers;

use DB;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\User;
use App\EveryGame;
use App\GameArchive;
use App\Order;

class UserAccountController extends Controller
{
	/**
	 * 日新增用户
	 */
	public function newIndex(Request $request)
	{
		$keywords = $request->input('keywords');
		$time = $request->input('time');
		$users = User::where('account', 'like', '%wx_%');
		if ($time) {
			$time_arr = explode('~', $request->input('time'));
			$begin = $time_arr[0];
			$end = $time_arr[1];
			$users = $users->whereBetween('created_at', [$begin, $end]);
		}
		if ($keywords) {
			$users = $users->where('nickname', 'like', '%'.$keywords.'%')->orWhere('userid', 'like', '%'.$keywords.'%');
		}
		$users = $users->orderBy('created_at', 'DESC')->paginate(15);
		$users = $users->appends([
			'keywords' => $keywords,
			'time' => $time
			]);

		return view('admin.useraccount.new', compact('users', 'keywords', 'time'));
	}

	/**
	 * 用户详情
	 */
	public function view(User $user)
	{
		return view('admin.useraccount.view', compact('user'));
	}

	/**
	 * [gameRecord description]
	 * @return [type] [description]
	 */
	public function gameRecord(User $user, Request $request)
	{
		$time = $request->input('time');
		$games = EveryGame::select(DB::raw('room_uuid, create_time, base_info'))->where(['user_id' => $user->userid]);
		if ($time) {
			$time_arr = explode('~', $request->input('time'));
			$begin = strtotime($time_arr[0]);
			$end = strtotime($time_arr[1]);
			$games = $games->whereBetween('create_time', [$begin, $end]);
		}
		$games = $games->orderBy('create_time', 'DESC')->groupBy('room_uuid')->get();

		return view('admin.useraccount.gamelog', compact('games', 'time'));
	}

	/**
	 * [gameDetail description]
	 * @return [type] [description]
	 */
	public function gameDetail(Request $request)
	{
		$game = GameArchive::where(['room_uuid' => $request->input('room_uuid')])->first();
		$history = json_decode($game->history, true);
		$infos = $history['seats'];
		$users = [];
		foreach ($infos as $info) {
			$user = User::where(['userid' => $info['userid']])->first();
			$name = $user->nickname ? $user->nickname : base64_decode($user->name);
			array_push($users, ['name' => $name, 'avatar' => $user->headimg, 'score' => $info['score']]);
		}
		return view('admin.useraccount.gamedetail', compact('users'));
	}

	/**
	 * [costRecord description]
	 * @return [type] [description]
	 */
	public function costRecord(User $user, Request $request)
	{
		$costs = Order::where(['user_id' => $user->userid, 'pay_status' => 1]);

		$costs = $costs->paginate(15);
		return view('admin.useraccount.costrecord', compact('costs'));
	}



}